import * as d3 from 'd3'
import * as topojson from 'topojson'
import toporoot from './chinaMap'
import api from '../../api/member'
import describeHtml from '../../public_components/describe'
const color = ['#8bfff0','#fff06f']
const atlasMap = {
  init(){
    let width = 0
    let height = 664
    let scale = 500
    const svgWidth = parseInt(d3.select('.map_content').style('width'))
    width = parseInt(d3.select('.map_content').style('width')) * 0.6
    height = parseInt(d3.select('.map_content').style('height'))
    let projection = this.projection = d3.geoMercator()
      .center([106, 34])
      .scale(scale)
      .translate([width / 2, height / 2])
    let path = d3.geoPath()
      .projection(projection)
    let georoot = topojson.feature(toporoot, toporoot.objects.china)
    let mergePolygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
      return true
    }))
    let svg = d3.select('svg.atlas_map').attr('transform', 'translate(' + 0 + ',' + 0 + ')').append('g').attr('transform', 'translate(' + 50 + ',' + 60 + ')').attr('class', 'gContainer')
    let china = svg.append('g').attr('class', 'china_map')
    china.append('path')
      .datum(mergePolygon)
      .attr('class', 'border')
      //          .style('fill', '#47a6ff')  // 用蓝色标注
      //        .style('fill-opacity', '0.1')
      // .style('fill', '#47a6ff')  // 用蓝色标注
      .style('fill', 'none')  // 用蓝色标注
      .style('fill-opacity', '0.1')
      .style('filter', 'url(#blue-glow)')
      .attr('stroke', '#82e3ff')
      .attr('stroke-opacity', '1')
      .attr('stroke-width', 2.5)
      .attr('d', path)

    // 添加中国各种的路径元素
   const mapPath = china.append('g').selectAll('path')
      .data(georoot.features)
      .enter()
      .append('path')
      .attr('cursor','pointer')
      .attr('class', 'province11')
      // .style('fill', function (d) {
      //   // console.log(d)
      //   // newValue = []
      //   // data.districts.forEach(function (val) {
      //   //   if (val.name === d.area_name) {
      //   //     newValue = [val]
      //   //   }
      //   // })
      //   // if (!newValue.length) {
      //   //   districtsValue = 0
      //   // } else {
      //   //   districtsValue = newValue[0].value
      //   // }
      //   // return 'rgba(84,180,220,'+ linear(districtsValue) +')'
      //   return 'red'
      // })
     .style('fill', 'none')
      .attr('d', path)
      .attr('stroke', '#82e3ff')
      .style('filter', 'url(#glow_line2)')
      .style('stroke-width', 0.5)
      .style('stroke-opacity', 0.5)


    api.mapData().then((res) => {
      res = JSON.parse(JSON.stringify(res))
      if (res.success) {
        const startColor = 'rgba(30,170,236,0.2)'
        const endColor = 'rgba(30,170,236,0.8)'
        // const startColor = 'rgba(20,179,203,0.6)'
        // const endColor = 'rgba(86,207,242,0.6)'
        let districtsValue = 0
        const mapData = res.data
        const priceData = Object.values(mapData)
        const max = d3.max(priceData, function (d) {
          return d
        })
        const linear = d3.scaleLinear()
          .domain([0, max])
          .range([0, 0.45])
        const color = d3.interpolate(startColor, endColor)
        var colorLinear = d3.scaleLinear()
          .domain([0, max])
          .range([0, 1]);
        mapPath.each(function (d, i, ele) {
          d3.select(ele[i])
            .style('fill', function (d) {
              districtsValue = mapData[d.properties.name] > 0 ? mapData[d.properties.name] : 0
              // return 'rgba(84,180,220,'+ linear(districtsValue) +')'
              return color(colorLinear(districtsValue))
            })
          })
          .on('click', function (d, i) {
            if (d.properties.name === '台湾') {
              alert('台湾省是中华人民共和国的领土，不可分割，神圣不可以侵犯')
              return false
            }
            d3.select('.relation_back').classed('hide', false)
            atlasMap.initRelation({province: d.properties.name})
          });

        const svgMap = d3.select('svg.atlas_map')
        const defs = svgMap.append("defs")
        const linearGradient = defs.append('linearGradient')
          .attr('id', "linearColor")
          .attr("x1", '0%')
          .attr('y1', '0%')
          .attr('x2', '100%')
          .attr('y2', '0%')
        const stop1 = linearGradient.append('stop')
          .attr('offset', "0%")
          .style("stop-color", startColor)
        const stop2 = linearGradient.append('stop')
          .attr('offset', "100%")
          .style("stop-color", endColor)
        let legendDotSize = 5;
        let legendG = svg.append('g')
          .attr('class', 'legendG')
          .attr('transform', 'translate(' + 50 + ',' + (height - 160) + ')')
        var legendText = legendG.selectAll("text")
          .data([0, max]);
        legendText.enter().append("text")
          .attr("y", 0)
          .attr("x", function (d, i) {
            return i ? 105 : -3
          })
          .attr('fill', function (d, i) {
            return '#70dafd'
          })
          // .style('filter', 'url(#blue-glow)')
          .attr('class', function (d, i) {
            return 'text' + i
          })
          .style('font-size', 12)
          .merge(legendText)
          .text(function(d) {
            return d;
          })

        legendText.exit().remove();

        // The dots of the legend
        var legendDot = legendG.selectAll("rect")
          .data([1]);

        legendDot.enter().append("rect")
          .attr("y", function(d, i) { return (i + 1) * legendDotSize; })
          .attr("width", 115)
          .attr("height", 25)
          .attr('class', function (d, i) {
            return 'rect' + i
          })
          .attr("fill", 'url(#linearColor)')
          .merge(legendDot)
      }
    })
    atlasMap.pointInit(1, svg, projection)
    d3.select('.close_back')
      .on('click', function () {
        d3.select('.relation_back').classed('hide', true)
      })
  },
  pointInit (page, svg, projection) {
    return false
    const height = parseInt(d3.select('.map_content').style('height'))
    api.pointData(page)
      .then((res) => {
        res = JSON.parse(JSON.stringify(res))
        if (res.success) {
          let legendData = []
          const data = res.data || {}
          const mapData = data.mapData || []
          mapData.forEach((val) => {
            legendData.push({
              key: val.key,
              name: val.name
            })
          })
          svg.select('.pointG').remove()
          svg.select('.legendG').remove()
          let pointG = svg.append('g')
            .attr('class', 'pointG')


          let legendDotSize = 20;
          let legendG = svg.append('g')
            .attr('class', 'legendG')
            .attr('transform', 'translate(' + 50 + ',' + (height - 160) + ')')
          var legendText = legendG.selectAll("text")
            .data(legendData);
          legendText.enter().append("text")
            .attr("y", function(d, i) { return i * legendDotSize + 6; })
            .attr("x", 15)
            .attr('fill', function (d, i) {
              return color[i]
            })
            .style('filter', 'url(#blue-glow)')
            .attr('cursor','pointer')
            .attr('class', function (d, i) {
              return 'text' + i
            })
            .style('font-size', 12)
            .merge(legendText)
            .text(function(d) {
              return d.name;
            })
          //   .on('click', function (m, i) {
          //     d3.select(this).classed('no_select', !d3.select(this).classed('no_select'))
          //     svg.selectAll('.rect' + i).classed('no_select', !d3.select('.rect' + i).classed('no_select'))
          // });

          legendText.exit().remove();

          // The dots of the legend
          var legendDot = legendG.selectAll("rect")
            .data(legendData);

          legendDot.enter().append("rect")
            .attr("y", function(d, i) { return i * legendDotSize - 3; })
            .attr("rx", legendDotSize * 0.5)
            .attr("ry", legendDotSize * 0.5)
            .attr("width", legendDotSize * 0.5)
            .attr("height", legendDotSize * 0.5)
            .attr('class', function (d, i) {
              return 'rect' + i
            })
            .attr('cursor','pointer')
            .attr("fill", function(d, i) { return color[i] })
            .style('filter', 'url(#blue-glow)')
            .merge(legendDot)
          // .on('click', function (m, i) {
          //   d3.select(this).classed('no_select', !d3.select(this).classed('no_select'))
          //   svg.selectAll('.text' + i).classed('no_select', !d3.select('.text' + i).classed('no_select'))
          // });

          legendDot.exit().remove();

          atlasMap.mapPoint(mapData, pointG, projection)
          setTimeout(function () {
            atlasMap.pointInit((data.currentPage + 1) > data.totalPage ? 1 : (data.currentPage + 1), svg, projection )
          }, 60 * 1000)
        }
      })
  },
  mapPoint(mapData, pointG, projection) {
    const  dotSize = 20
    let legendSelect = {}
    let pointData = []
    let copyMapData = mapData.slice(0)
    d3.select('.legendG').selectAll('text').each(function (d,i ,ele) {
      legendSelect[d.key] = !d3.select(ele[i]).classed('no_select')
    })
    copyMapData.forEach((val, i) => {
       if (legendSelect[val.key]) {
         val.data.forEach((point) => {
           point.color = color[i]
           pointData.push(point)
         })
       }
    })
    d3.selectAll('.pointRect').remove();
   const pointRect = pointG.selectAll('.pointRect')
      .data(pointData)

   const enterPoint = pointRect
      .enter().append('rect')
      .attr('class', function (d, i) {
        return 'pointRect'
      })
      .attr("x", function(d, i) {
        return projection([d.lng, d.lat])[0]
      })
      .attr("y", function(d, i) {
        return projection([d.lng, d.lat])[1]
      })
      .attr("rx", dotSize * 0.5)
      .attr("ry", dotSize * 0.5)
      .attr("width", dotSize * 0.5)
      .attr("height", dotSize * 0.5)
      .attr('cursor','pointer')
      .attr("fill", function(d, i) { return d.color })
      .attr('filter', 'url(#hospital-glow)')
      .merge(pointRect)
      .on('click', function (d, i) {
        d3.select('.relation_back').classed('hide', false)
        d3.select('#title_name').text(d.name)
        atlasMap.initRelation(d.id)

      })
      .on('mouseover', function (d, i, ele) {
        d3.select(ele[i])
          .attr("width", dotSize)
          .attr("height", dotSize)
      })
      .on('mouseout', function (d, i, ele) {
        d3.select(ele[i])
          .attr("width", dotSize * 0.5)
          .attr("height", dotSize * 0.5)
      })

    enterPoint.append("title")
      .text(function(d) { return d.name; });
  },
  initRelation (parame) {
    var color = {
      'hospital': '#8bfff0',
      'site': '#fff06f'
    }
    d3.select('.node_title').remove()
    const svg = d3.select("svg.relation_map"),
      content = d3.select(".relation_svg_container"),
      width = +content.node().offsetWidth,
      height = +content.node().offsetHeight;
    svg.selectAll('g').remove();
    api.relationData(parame).then((res) => {
      res = JSON.parse(JSON.stringify(res))
      if (res.success) {
        const data = res.data || {}
        const relationData = data.relationData
        d3.select('#title_name').text(data.centerName)
          .attr('title', data.centerName)
        let briefValue = Object.values(JSON.parse(data.brief))
        if (typeof briefValue[0] !== 'string') {
          briefValue[1] = briefValue[0].hospital + briefValue[1]
          briefValue.shift()
        }
        // d3.select('#relation_describe').text(data.brief)
        describeHtml('#relation_describe', {
          lists: briefValue
        }, true)
        let legendData = []
        let has = false
        let keyName = ''
        relationData.nodes.forEach((val) => {
          has = false
          legendData.forEach((legend) => {
            if (legend.key === val.key) {
              has = true
            }
          })
          if (!has) {
            if (val.key === 'hospital') {
              keyName = '采购方'
            }
            else if (val.key === 'site') {
              keyName = '供应商'
            }
            legendData.push({
              key: val.key,
              name: keyName
            })
          }
        })
        var nodeMax = d3.max(relationData.nodes, function (d) {
          return d.value
        })
        var nodeMin = d3.min(relationData.nodes, function (d) {
          return d.value
        })
        var linkMax = d3.max(relationData.links, function (d) {
          return Number(d.value)
        })
        var linkMin = d3.min(relationData.links, function (d) {
          return Number(d.value)
        })
        //
        // var nodeScale = d3.scaleLinear().domain([nodeMin, nodeMax])
        //   .range([5, 10])
        var linkScale = d3.scaleLinear().domain([linkMin, linkMax])
          .range([1.5, 2.8])

        var simulation = d3.forceSimulation()
          .force("link", d3.forceLink().id(function(d) { return d.id; }))
          .force("collide",d3.forceCollide( function(d){
              return  5
          }).strength(0.2).iterations(2)
          )
          .force("charge", d3.forceManyBody())
          .force("center", d3.forceCenter(width * 0.6 / 2, height / 2));

        var link = svg.append("g")
          .attr("class", "links")
          .selectAll("line")
          .data(relationData.links)
          .enter().append("line")
          .attr('stroke', 'rgba(112,218,253, 0.5)')
          .attr('stroke-dasharray', function (d) {
            return d.value >=0 ? 0 : 3
          })
          .attr("stroke-width", function(d) {
            return Number(d.value) >=0 ? linkScale(Number(d.value)): 2;
            // return 2
          });

        var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(relationData.nodes)
          .enter().append("circle")
          .attr('filter', 'url(#blue-glow)')
          .attr("r", function (d, i) {
            // return nodeScale(d.value)
            return data.centerId  === d.id ? 6 : 4
          })
          .attr('cursor','pointer')
          .attr("fill", function(d) { return color[d.key]; })
          .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended))
          .on("click", function (d) {
            atlasMap.initRelation({id: d.id})
          })
          .on("mouseover", function (d) {
            console.log()
            d3.select('.node_title').remove()
            d3.select('.relation_svg_container')
              .selectAll('.node_title')
              .data([{
                name: d.name,
                x:d.x,
                y:d.y
              }])
              .enter().append('div')
              .attr('class', 'node_title')
              .style('left', function (d) {
                return (d.x + 6) + 'px'
              })
              .style('top', function (d) {
                return (d.y + 6) + 'px'
              })
              .text(function (d) {
                return d.name
              })
          })
          .on("mouseout", function (d) {
            d3.select('.node_title').remove()
          })

        ;

        // node.append("title")
        //   .text(function(d) { return d.name; });

        simulation
          .nodes(relationData.nodes)
          .on("tick", ticked);

        simulation.force("link")
          .links(relationData.links);

        function ticked() {
          link
            .attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

          node
            .attr("cx", function(d) {
              if (d.x > width * 0.6) {
                d.x = d.x - width * 0.67
              }
              if (d.x < 0) {
                d.x = 90 - d.x
              }
              return d.x;
            })
            .attr("cy", function(d) {
              if (d.y > height) {
                d.y = d.y - height - 20
              }
              if (d.y < 0) {
                d.y = 120 - d.y
              }
              return d.y;
            });
        }


        function dragstarted(d) {
          if (!d3.event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
        }

        function dragged(d) {
          d.fx = d3.event.x;
          d.fy = d3.event.y;
        }

        function dragended(d) {
          if (!d3.event.active) simulation.alphaTarget(0);
          d.fx = null;
          d.fy = null;
        }

        let legendDotSize = 20;
        let legendG = svg.append('g')
          .attr('class', 'legendG')
          .attr('transform', 'translate(' + 20 + ',' + (height - 40 ) + ')')
        let legendText = legendG.selectAll("text")
          .data(legendData);
        legendText.enter().append("text")
          .attr("y", function(d, i) { return i * legendDotSize + 6; })
          .attr("x", 15)
          .attr('fill', function (d, i) {
            return color[d.key]
          })
          .style('filter', 'url(#blue-glow)')
          // .attr('cursor','pointer')
          .attr('class', function (d, i) {
            return 'text' + i
          })
          .style('font-size', 12)
          .merge(legendText)
          .text(function(d) {
            return d.name;
          })

        legendText.exit().remove();

        // The dots of the legend
        let legendDot = legendG.selectAll("rect")
          .data(legendData);

        legendDot.enter().append("rect")
          .attr("y", function(d, i) { return i * legendDotSize - 3; })
          .attr("rx", legendDotSize * 0.5)
          .attr("ry", legendDotSize * 0.5)
          .attr("width", legendDotSize * 0.5)
          .attr("height", legendDotSize * 0.5)
          .attr('class', function (d, i) {
            return 'rect' + i
          })
          // .attr('cursor','pointer')
          .attr("fill", function(d, i) { return color[d.key] })
          .style('filter', 'url(#blue-glow)')
          .merge(legendDot);

        legendDot.exit().remove();
      }
    })
  }
}

export default atlasMap